
package com.jf.cloud.multishop.controller.platform;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.PhoneUtil;
import com.jf.cloud.api.auth.constant.SysTypeEnum;
import com.jf.cloud.api.auth.dto.AuthAccountDTO;
import com.jf.cloud.api.auth.feign.AccountFeignClient;
import com.jf.cloud.api.auth.vo.AuthAccountVO;
import com.jf.cloud.api.multishop.constant.ShopStatus;
import com.jf.cloud.api.multishop.vo.ShopDetailVO;
import com.jf.cloud.api.platform.dto.OfflineHandleEventDTO;
import com.jf.cloud.common.constant.Constant;
import com.jf.cloud.common.database.dto.PageDTO;
import com.jf.cloud.common.database.vo.PageVO;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.multishop.constant.IsPreferred;
import com.jf.cloud.multishop.dto.*;
import com.jf.cloud.multishop.service.ShopDetailService;
import com.jf.cloud.multishop.vo.ShopHeadInfoVO;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 店铺详情
 *
 * @author zz
 * @date 2020-12-05 15:50:25
 */
@RestController("platformShopDetailController")
@RequestMapping("/p/shop_detail")
@Tag(name = "platform-店铺信息")
public class ShopDetailController {

    @Value("${jfcloud.expose.operation.auth:}")
    private Boolean permission;

    @Autowired
    private ShopDetailService shopDetailService;
    @Autowired
    private MapperFacade mapperFacade;
    @Autowired
    private AccountFeignClient accountFeignClient;

    @GetMapping("/page")
    @Operation(summary = "分页查询" , description = "分页查询")
    public ServerResponseEntity<PageVO<ShopDetailVO>> getShopAuditingPage(PageDTO pageDTO, ShopDetailDTO shopDetailDTO) {
        if (!Objects.equals(Constant.PLATFORM_SHOP_ID, AuthUserContext.get().getTenantId())) {
            throw new LuckException(ResponseEnum.UNAUTHORIZED);
        }
        return ServerResponseEntity.success(shopDetailService.page(pageDTO, shopDetailDTO));
    }

    @GetMapping("/info")
    @Operation(summary = "获取店铺基本信息" , description = "获取店铺基本信息")
    public ServerResponseEntity<ShopDetailVO> getInfo(@RequestParam Long shopId) {
        ShopDetailVO shopDetailVO = shopDetailService.getByShopId(shopId);
        if (BooleanUtil.isFalse(permission)) {
            shopDetailVO.setContactPhone(PhoneUtil.hideBetween(shopDetailVO.getContactPhone()).toString());
        }
        ServerResponseEntity<AuthAccountVO> responseEntity = accountFeignClient.getAccountInfoByTenantId(shopId, SysTypeEnum.MULTISHOP.value());
        if (responseEntity.isSuccess() && Objects.nonNull(responseEntity.getData())) {
            AuthAccountVO authAccountVO = responseEntity.getData();
            if (BooleanUtil.isFalse(permission)) {
                shopDetailVO.setMerchantAccount(PhoneUtil.hideBetween(authAccountVO.getPhone()).toString());
            } else {
                shopDetailVO.setMerchantAccount(authAccountVO.getPhone());
            }
            shopDetailVO.setAccountStatus(authAccountVO.getStatus());
        }
        return ServerResponseEntity.success(shopDetailVO);
    }

    /**
     * 新建店铺
     */
    @PostMapping("/create_shop")
    @Operation(summary = "新建店铺" , description = "新建店铺")
    public ServerResponseEntity<Void> createShop(@RequestBody ShopCreateInfoDTO shopCreateInfoDTO) {
        shopDetailService.platformCreateShop(shopCreateInfoDTO);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @Operation(summary = "编辑店铺基本信息" , description = "编辑店铺基本信息")
    public ServerResponseEntity<Void> editShop(@RequestBody ShopDetailDTO shopDetailDTO) {
        if (Objects.isNull(shopDetailDTO.getShopId())) {
            throw new LuckException("店铺id不能为空");
        }
        shopDetailService.update(shopDetailDTO);
        return ServerResponseEntity.success();
    }

    @PutMapping("/update_signing_info")
    @Operation(summary = "更新店铺签约信息" , description = "更新店铺签约信息")
    public ServerResponseEntity<Void> updateSigningInfo(@RequestBody @Valid ShopSigningInfoDTO shopSigningInfoDTO) {
        if (Objects.isNull(shopSigningInfoDTO.getShopId())) {
            throw new LuckException("店铺id不能为空");
        }
        shopDetailService.updateSigningInfo(shopSigningInfoDTO);
        return ServerResponseEntity.success();
    }

    @PutMapping("/update_shop_preferred")
    @Operation(summary = "当前店铺为优选，则取消优选;不是优选，则设置为优选" , description = "当前店铺为优选，则取消优选;不是优选，则设置为优选")
    public ServerResponseEntity<Void> updateShopPreferred(@RequestParam(value = "shopId", required = true) Long shopId) {
        ShopDetailVO shopDetailVO = shopDetailService.getByShopId(shopId);
        shopDetailVO.setIsPreferred(Objects.equals(shopDetailVO.getIsPreferred(), IsPreferred.YES.value()) ? IsPreferred.NO.value() : IsPreferred.YES.value());
        shopDetailService.update(mapperFacade.map(shopDetailVO, ShopDetailDTO.class));
        return ServerResponseEntity.success();
    }

    @PutMapping("/update_password")
    @Operation(summary = "更新店铺商家的登陆密码" , description = "更新店铺商家的登陆密码")
    public ServerResponseEntity<Void> updatePassword(@RequestBody ShopAccountDTO shopAccountDTO) {
        // 暂时的home的店铺id
        Long home = 4L;
        if (Objects.equals(shopAccountDTO.getShopId(), home) && BooleanUtil.isFalse(permission)) {
            throw new LuckException("暂无权限修改该用户账号信息");
        }
        ServerResponseEntity<AuthAccountVO> merchantInfoByTenantId = accountFeignClient.getAccountInfoByTenantId(shopAccountDTO.getShopId(), SysTypeEnum.MULTISHOP.value());
        if (!merchantInfoByTenantId.isSuccess()) {
            throw new LuckException("服务异常");
        }
        AuthAccountVO authAccountVO = merchantInfoByTenantId.getData();
        authAccountVO.setPassword(shopAccountDTO.getPassword());
        accountFeignClient.update(mapperFacade.map(authAccountVO, AuthAccountDTO.class));
        return ServerResponseEntity.success();
    }

    @PutMapping("/offline")
    @Operation(summary = "下线店铺" , description = "下线店铺")
    public ServerResponseEntity<Void> offline(@RequestBody OfflineHandleEventDTO offlineHandleEventDTO) {
        Long sysUserId = AuthUserContext.get().getUserId();
        ShopDetailVO shopDetailVO = shopDetailService.getByShopId(offlineHandleEventDTO.getHandleId());
        if (Objects.isNull(shopDetailVO)) {
            throw new LuckException("未找到该店铺信息");
        }
        if (!Objects.equals(shopDetailVO.getShopStatus(), ShopStatus.OPEN.value()) && !Objects.equals(shopDetailVO.getShopStatus(), ShopStatus.STOP.value())) {
            throw new LuckException("店铺不处于营业或者停业状态,不能进行下线");
        }
        shopDetailService.offline(shopDetailVO, offlineHandleEventDTO.getOfflineReason(), sysUserId);


        return ServerResponseEntity.success();
    }

    @GetMapping("/count_by_shop_status")
    @Operation(summary = "根据店铺状态查询店铺数量" , description = "根据店铺状态查询店铺数量")
    public ServerResponseEntity<Long> countByShopStatus(@RequestParam(value = "shopStatus", required = false, defaultValue = "3") Integer shopStatus) {
        Long countByShopStatus = shopDetailService.countByShopStatus(shopStatus);
        return ServerResponseEntity.success(countByShopStatus);
    }

    @PostMapping("/online_audit")
    @Operation(summary = "店铺违规下线，重新申请上线审核" , description = "店铺违规下线，重新申请上线审核")
    public ServerResponseEntity<Void> onlineAudit(@RequestBody OfflineHandleEventDTO offlineHandleEventDTO) {
        shopDetailService.onlineAudit(offlineHandleEventDTO);
        return ServerResponseEntity.success();
    }

    @GetMapping("/search_shops")
    @Operation(summary = "platform搜索店铺" , description = "根据店铺名称搜索店铺")
    public ServerResponseEntity<PageVO<ShopHeadInfoVO>> searchShops(PageDTO pageDTO, ShopSearchDTO shopSearchDTO) {
        PageVO<ShopHeadInfoVO> shopPage = shopDetailService.renovationShopPage(pageDTO, shopSearchDTO, SysTypeEnum.PLATFORM.value());
        return ServerResponseEntity.success(shopPage);
    }

    @GetMapping("/group_area_count")
    @Operation(summary = "地区分组获取店铺数量" , description = "地区分组获取店铺数量")
    public ServerResponseEntity<List<Map<String,Object>>> group_area_count(@RequestParam(value = "cateId", required = false) Long cateId) {
        return ServerResponseEntity.success(shopDetailService.group_area_count(cateId));
    }
}
